package com.ilxqx.generator.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.StringBuilderWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;

@Slf4j
public final class TemplateUtils {

    private static final Configuration CONFIGURATION;

    static {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setEncoding(Locale.CHINA, "utf-8");
        configuration.setOutputEncoding("UTF-8");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        configuration.setDateFormat("yyy-MM-dd");
        configuration.setTimeFormat("HH:mm:ss");
        configuration.setBooleanFormat("true,false");
        TemplateLoader templateLoader = new ClassTemplateLoader(TemplateUtils.class.getClassLoader(), "templates");
        configuration.setTemplateLoader(templateLoader);

        CONFIGURATION = configuration;
    }

    public static void render(String templatePath, Object data, Writer writer) {
        try {
            Template template = CONFIGURATION.getTemplate(templatePath, "utf-8");
            log.info("开始渲染模板【{}】", templatePath);
            template.process(data, writer);
        } catch (IOException e) {
            log.error("模板【{}】加载失败", templatePath, e);
            throw new RuntimeException("模板加载失败");
        } catch (TemplateException e) {
            log.error("模板【{}】渲染失败", templatePath, e);
            throw new RuntimeException("模板渲染失败");
        }
    }

    public static String render(String templatePath, Object data) {
        StringBuilderWriter writer = new StringBuilderWriter();
        render(templatePath, data, writer);
        return writer.toString();
    }

    public static void render(String templatePath, Object data, File file) {
        try {
            FileWriter writer = new FileWriter(file);
            render(templatePath, data, writer);
        } catch (IOException e) {
            log.error("文件【{}】出现错误", file.getName(), e);
        }
    }

}
